<template>
    <div class="e-form">
        <div class="tabs">
            <div class="tabs-title">基本信息</div>
            <el-form ref="form" :model="formData" label-width="160px" :rules="rules">

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="结算编号：">
                           <el-input v-model="formData.settleNo" :disabled="isDisabled" readonly="true">
                                {{formData.settleNo }}
                           </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机构：">
                            <el-input v-model="formData.orgName" disabled="treu">
                                <span>{{ formData.orgName }}</span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="业务类型" prop="businessTypeKey">
                            <el-select
                                v-model="formData.businessTypeKey"
                                placeholder="请选择"
                                :disabled="true"
                                @change="busTypeChange"
                            >
                                  <el-option
                                  v-for="(
                                    item
                                    ) in businessDtlLists"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                    >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="源单编号：" prop="sourceNo">
                            <el-input v-model="formData.sourceNo " disabled="true">
                                <span>{{formData.sourceNo }}</span>
                            </el-input>

                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="结算单位">
                            <el-input placeholder="请选择结算单位" v-model="formData.settleOrg" class="input-with-select"
                                :disabled="true">
                                <el-button slot="append" @click="settleOrgChange">选择结算明细</el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结算类型：" prop="settleType">
                           <el-input v-model="formData.settleType" disabled="true">
                                <span>{{formData.settleType }}</span>
                           </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="发票号" prop="invoiceNo">
                            <el-input v-model="formData.invoiceNo"
                                :disabled="true">
                                 <span>{{formData.invoiceNo }}</span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="录入人员：">
                            <el-input disabled='true' v-model='formData.inputName'>
                                <span>{{formData.inputName}}</span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="不含税金额(元)" >
                            <el-input v-model="formData.taxExcluding"
                             @change="e =>{
                                amountExcludingTaxHandel(e)
                                }"
                                :disabled="true"
                            >
                            <span>
                                {{formData.taxExcluding}}
                            </span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="结算日期：" v-model="formData.settleDate">
                            <el-date-picker
                                :disabled="true"
                                v-model="formData.settleDate"
                                type="date"
                                placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="税率" prop="taxRate" >
                             <el-input v-model="formData.taxRate" placeholder="展示为%"
                                :disabled="true"
                             @change="e =>{taxRateHandel(e)}"
                             >
                                <span>{{formData.taxRate}}</span>
                           </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="税价合计：">
                           <el-input v-model="formData.totalTaxPrice" disabled="true">
                                <span>{{formData.totalTaxPrice}}</span>
                           </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="税额：" >
                            <el-input placeholder="业务类型对应的源单带入" class="input-with-select" v-model="formData.taxAmount"
                                :disabled="true"
                            @change="e =>{
                                contractAmount(e)
                                }"
                            >
                              <span>
                                    {{formData.taxAmount}}
                              </span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="累计结算金额：">
                           <el-input v-model="formData.cumulativeSettleAmount" disabled="true"
                            @change='e =>{
                                exchangeRateChange(e)
                            }'>
                                <span>{{ formData.cumulativeSettleAmount }}</span>
                           </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="服务单位费用(含税，元)：" >
                            <el-input placeholder="" v-model="formData.transportUnitCost" class="input-with-select"
                                :disabled="true"
                            @change="e =>{transportUnitCostHandel(e)}"
                            >
                                <span>
                                    {{formData.transportUnitCost}}
                                </span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="单据来源：" prop="billSource">
                            <el-input v-model="formData.billSource"
                                :disabled="true">
                                <span>{{ formData.billSource }}</span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冲预付款金额(元)：" >
                              <el-checkbox v-model="checkedBox" @change='changeHandel'>
                                   <span>
                                {{formData.advanceChargeAmount}}
                            </span>
                              </el-checkbox>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="验收编号：">
                            <el-input v-model="formData.acceptanceNo"
                                :disabled="true">
                               <span>{{ formData.acceptanceNo }}</span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冲个人借支：">
                            <el-checkbox @change="checkHandel" :checked="checkPerson" :disabled="formData.businessTypeKey != '1'"></el-checkbox>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="终期结算：">
                            <el-checkbox v-model="setFinalSettle" @change="checkToF"></el-checkbox>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冲个人借支金额(元)：" >
                            <el-input placeholder=""  v-model="formData.rushPersonalBorrowingAmount" class="input-with-select"
                            :disabled="checkPerson?false:true" @change="personHandel"
                            >
                                <span>
                                    {{formData.rushPersonalBorrowingAmount}}
                                </span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="币种：">
                                <el-select
                                :disabled="true"
                                v-model="formData.currency"
                                placeholder="请选择"
                                @change="currencyChange"
                            >
                                <el-option
                                    v-for="(
                                        item
                                    ) in currencyForm"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                >
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="冲销对象：" :prop="reversalObjectName">
                             <el-input placeholder="请输入内容" class="input-with-select" v-model="formData.reversalObjectName"
                                :disabled="checkPerson?false:true">
                                <el-button slot="append" @click='handelChange' :disabled="chooseHandel">选择</el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态：" >
                            {{shuziShow(formData.state)}}
                            <!-- <el-input placeholder="" v-model="formData.state" class="input-with-select" disabled="true">
                              <template slot-scope="{ row }">
                                    {{shuziShow(row.state)}}
                                </template>
                            </el-input> -->
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="借支人员：" >
                            <el-input placeholder="" class="input-with-select"  v-model="formData.borrower" :disabled="checkPerson?false:true" >
                                  <el-button slot="append" @click='getSigningName'>选择</el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注：" >
                            <el-input placeholder="" v-model="formData.remarks" class="input-with-select" type="textarea"
                            :rows="3">
                            <span>
                                {{formData.remarks}}
                            </span>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="12">
                        <!-- 仅发生冲红单业务时,才显示该字段,暂未做判断 -->
                        <el-form-item label="冲红单:">
                            <div :style="redBillStatusStyle">{{ redBillStatusFun(formData.redStatus) }}</div>
                           <!-- <el-input
                                :style="redBillStateStyle"
                                v-model='formData.redstate'
                            >
                                <span slot="prefix">fdfd</span>
                            </el-input> -->
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="传输财务共享：">
                            <span :class="isFontColor ? 'redFont' : 'greenFont'">{{shareLable(formData.transferFinancialShare)}}</span>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
        <div class="buttons">
            <el-button
                type="primary"
                size="small"
                class="btn-blue"
                @click="preserve"
                v-debounce
                >保存</el-button
            >
            <el-button size="small" @click="handleClose"  v-debounce>取消</el-button>
        </div>
    </div>
</template>

<script>
import request from '@/api/PCCset/apply.js'
import { getRmbRate } from '@/api/equip/common.js'
import { mapState } from 'vuex'
import { selectDataClient, showLoading, hideLoading, formatDate } from '@/utils/common'
// import NewPlanBillingDetails from './NewPlanBillingDetails.vue'
export default {
    data () {
        return {
            chooseHandel: true,  //是否能选择冲销对象
            setFinalSettle: false,
            checkPerson: false,
            optionssettleOrg: [{         //冲销对象
                valuesettleOrg: '1',
                label: '结算单位',
            }, {
                valuesettleOrg: '2',
                label: '服务服务单位'
            }],
            valuesettleOrg: '',
            businessDtlLists: [{         //业务类型
                value: '1',
                label: '临时需用计划',
            }, {
                value: '2',
                label: '物资采购合同'
            }, {
                value: '3',
                label: '调拨单'
            }],
            // businessDtlLists: ['临时需用计划', '物资采购合同', '调拨单'],
            value: '',
            // checkedBox: false,
            dataList: {},
            value1: '',
            formData: {
                'acceptanceNo': '',
                'advanceChargeAmount': 0,
                'baseCurAmount': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'billId': '',
                'billNo': '',
                'billSource': 0,
                'borrower': '',
                'businessTypeKey': 0,
                'businessTypeValue': '',
                'cumulativeSettleAmount': 0,
                'currency': '',
                'currencyId': '',
                'evaluationGrade': 0,
                'inputId': '',
                'inputName': '',
                'invoiceNo': '',
                'isFinalSettle': 0,
                'isRed': 0,
                'isRushAdvanceCharge': 0,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDesciption': '',
                'nullifyReason': '',
                'orgId': '',
                'orgName': '',
                'parentId': '',
                'redStatus': 0,
                'remarks': '',
                'reversalObjectId': 0,
                'reversalObjectName': 0,
                'rmbAmount': 0,
                'rmbRate': 0,
                'rushPersonalBorrowing': 0,
                'rushPersonalBorrowingAmount': 0,
                'settleDate': formatDate(new Date(), 'yyyy-MM-dd'), //结算日期,
                'settleOrg': '',
                'settleOrgId': '',
                'settleType': 0,
                'sourceId': '',
                'sourceNo': '',
                'state': 0,
                'taxAmount': 0,
                'taxExcluding': 0,
                'taxRate': 0,
                'totalTaxPrice': 0,
                'transferFinancialShare': 0,
                'transportUnitCost': 0,
                'workId': ''
            },
            rules: {
                advanceChargeAmount: [
                    { required: true, message: '请填写冲预付款金额为必填项', trigger: 'change' }
                ],
                settleNo: [
                    { required: true, message: '请填写结算编号', trigger: 'blur' }
                ],
                orgName: [
                    { required: true, message: '请填写机构名称', trigger: 'blur' }
                ],
                businessTypeKey: [
                    { required: true, message: '请选择业务类型', trigger: 'change' }
                ],
                settleDate: [
                    { required: true, message: '请选择结算日期', trigger: 'blur' }
                ],
                settleOrg: [
                    { required: true, message: '请选择冲销对象', trigger: 'change' }
                ],
                taxRate: [
                    { required: true, message: '请填写税率，可填范围0~100', trigger: 'blur' }
                ],
                billSource: [
                    { required: true, message: '请填写单据来源', trigger: 'blur' }
                ],
                invoiceNo: [
                    { required: true, message: '请填写发票号', trigger: 'blur' }
                ],
                remarks: [
                    { max: 500, message: '长度不超过500个字符', trigger: 'blur' }
                ],
            },
            isDisabled: false,
            test: '',
            isFontColor: true, //传输财务共享颜色  未传，返回修改 红色   财务共享审核中，已传 绿色
            relationId: this.$route.query.relationId,
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            leaseTypeList: state => state.equip.equipData.leaseTypeList, //租赁类型
        }),

        // totalData () {
        //     return param=> {
        //         const state =  this.$store.state.equip.equipData.state
        //         const obj = state.find(x=>x.value === param)
        //         return (obj ?  obj.label :  '')
        //     }
        // },
        //传输财务共享
        shareLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.shareFrom
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
        // totalTaxPrice () {
        //     return this.formData.cumulativeSettleAmount + this.formData.taxAmount
        // }
    },
    created () {
        const date = new Date()
        this.formData.settleDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
        this.formData.inputName = localStorage.getItem('userName')
        this.getInInfo ()
        this.billId = this.$route.query.billId
        this.billid = this.$route.query.billid
        const { baseCyByOrgId } = this.userInfo
        this.formData.baseCurName = baseCyByOrgId.currencyName  //本位币
        this.formData.baseCurName = baseCyByOrgId.currency
        // this.getRedList()
    },
    components: {
        // NewPlanBillingDetails
    },
    mounted () {
        const redData = this.$route.params.redData
        this.formData = redData
        console.log(this.formData.cumulativeSettleAmount, 'hfffffff')
    },
    methods: {
        //状态红单
        redBillStatusFun (redStatus) {
            if(redStatus == 1) {
                return '冲销中'
            }else if(redStatus == 2) {
                return '已冲销'
            }else if(redStatus == 3) {
                return '红单'
            }else if(redStatus == -1) {
                return '未冲销'
            }
        },
        //状态数字转换
        shuziShow (state) {
            if(state == -1) {
                return '已删除'
            }else if(state == 0) {
                return '草稿'
            }else if(state == 1) {
                return '审核中'
            }else if(state == 2) {
                return '已审核'
            }else if(state == 5) {
                return '已作废'
            }
        },
        // 点击冲红单进入返显数据,备注能修改
        // async getRedList () {
        getRedList () {
            showLoading()
            request.PccSetCorresData({ billId: this.$route.query.billId }).then(res =>{
                this.checkedBox = res.advanceChargeAmount === 0 ? false : true
                this.formData = res
                // this.redFormData = this._.cloneDeep(this.formData)
                // console.log(this.redFormData, 'this.redFormData')
                this.formData.businessTypeKey = this.businessDtlLists.find(
                    item => item.label === this.formData.businessTypeValue
                ).label
                // data.currency = this.currencyForm.find(
                //     x => x.value === data.currencyId
                // ).label
                this.formData.busi
                console.log( this.formData)
                console.log(this.formData.businessTypeValue)
            })
            hideLoading()
        },
        //币种切换
        currencyChange (val) {
            this.formData.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种
            if (this.formData.currency === '人民币') {
                this.formData.rmbRate = 1
            } else {
                getRmbRate({
                    //获取机构下某币种的人民币汇率
                    currency: val,
                    orgId: this.userInfo.orgInfo.orgId
                })
                    .then(res => {
                        this.formData.rmbRate = res.rate
                    })
                    .catch(() => {})
            }
            if (this.formData.currency === this.formData.baseCurName) {
                //币种=本位币
                this.formData.baseCurRate = 1
                this.showBaseCurName = false
            } else {
                this.formData.baseCurRate = null
                this.showBaseCurName = true
            }
        },
        //终期结算
        checkToF () {
            console.log(111)
            if(this.setFinalSettle == true) {
                console.log(this.setFinalSettle)
                this.formData.isFinalSettle == 1
                console.log(this.formData.isFinalSettle)
            }else{
                this.formData.isFinalSettle == 0
            }
        },
        //获取借支人员
        getSigningName ()  {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/hr/user/getUserUnderOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify({ 'orgId': this.formData.orgId }),    // 接口参数
                Title: '选择借支人员' // 标题
            }).then(val => {
                this.formData.borrower = val[0].userName
            })
        },
        //金额类数据  1、税价合计   2、税额
        taxRateHandel (e) {
            //税率
            if(0 <= e && e < 100) {
                this.formData.taxRate = e + '%'
                // this.formData.taxRate = e
                if(this.formData.taxExcluding && parseInt(this.formData.taxRate)) {
                    this.formData.taxAmount = ( parseInt(this.formData.taxRate) * this.formData.taxExcluding) / 100
                }
            }else{
                this.$message.warning('税率填写范围为0~100')
            }
        },
        amountExcludingTaxHandel (e) {
            //不含税金额
            this.formData.taxExcluding = e
            if(this.formData.taxExcluding &&  parseInt(this.formData.taxRate)) {
                this.formData.taxAmount = ( parseInt(this.formData.taxRate) * this.formData.taxExcluding) / 100
            }
        },
        contractAmount (e) {
            // 税额
            this.formData.taxAmount = e
            if (this.formData.taxExcluding && this.formData.taxAmount || this.formData.advanceChargeAmount) {
                this.formData.totalTaxPrice = Math.ceil(parseInt((this.formData.taxExcluding) + parseInt(this.formData.taxAmount) + parseInt(this.formData.advanceChargeAmount)) * 100) / 100   //税价合计
                this.formData.taxAmount = Math.ceil(this.formData.taxAmount * this.formData.taxExcluding) * 100 / 100
            }
        },
        advanceChargeAmountHandel (e) {
            //冲预付款金额
            this.formData.advanceChargeAmount = e
            if (this.formData.taxExcluding && this.formData.taxAmount || this.formData.advanceChargeAmount) {
                this.formData.totalTaxPrice = Math.ceil(parseInt((this.formData.taxExcluding) + parseInt(this.formData.taxAmount) + parseInt(this.formData.advanceChargeAmount)) * 100) / 100   //税价合计
            }
        },
        transportUnitCostHandel (e) {
            //服务费用
            this.formData.transportUnitCost = e
            this.formData.cumulativeSettleAmount = Math.ceil(this.formData.totalTaxPrice + parseInt(this.formData.transportUnitCost)) * 100 / 100
        },
        //
        //选择业务类型
        busTypeChange () {
            const findObj = this.businessDtlLists.find(item => item.value === this.formData.businessTypeKey)
            this.formData.businessTypeValue = findObj.label
        },
        //冲个人借支金额
        personHandel (e) {
            if(e && (e <= this.formData.totalTaxPrice)) {
                this.formData.totalTaxPrice = e
            }else {
                this.formData.totalTaxPrice = ''
            }
        },
        //冲个人借支
        checkHandel () {
            if(this.checkPerson == true) {
                this.checkPerson = false
                console.log(222222)
            }else{
                this.checkPerson = true
                alert('确认冲个人借资？')
            }
        },
        //冲销对象
        handelChange () {
            selectDataClient({
                SelectServiceToken: '/facilityconnect/lease/receive/plan/contract/receive', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                InitParamsStr: JSON.stringify({ 'billId': this.formData.billid }),    // 接口参数(name为模拟参数)
                Title: '选择冲销人员' // 标题
            }).then(val => {
                console.log(val, 'vv')
            })
            // }else{
            //     this.chooseHandel = true
            // }
        },
        checkedHandel () {
            // if(checked == true) {
            //     this.message('冲预付款金额为必填项')
            // }
        },
        //获取默认数据
        getInInfo () {
            this.formData.writeName = localStorage.getItem('userName')  // 缺少字段
        },
        //点击结算单位按钮
        settleOrgChange () {
            // 弹窗选择数据
            let ids = []
            selectDataClient({
                SelectServiceToken: '/turnover/acceptance/selectSettleDtl', // 获取选择结算明细
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify({  'businessTypeKey': '1',
                    'keyWord': '',
                    'parentId': '0' }),
                Title: '选择结算单位数据' // 标题
            }).then(val => {
                this.formData.settleOrg = val[0].settleOrgName
            })
        },
        // 弹窗选择结算编号
        selectPlanNo () {
            if(this.isDisabled) {
                return
            }
            let ids = []
            selectDataClient({
                SelectServiceToken: '/facilityplan/get/configuration/plan', // 客户端对应方法名   待修改数据@@@@@
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                Title: '选择结算编号' // 标题
            }).then(val => {
                this.formData.settleNo = val[0].billNo
                this.formData.billId = val[0].billId
            })
        },
        //保存
        preserve () {
            request.PccSetNewDataInfo({ ...this.formData }).then(res=>{
                this.clientPop('info', '保存成功!是否进行下一步操作？', ()=>{
                    this.$router.push({
                        path: '/NewPlanDetailRed',
                        query: {
                            billid: res,
                            name: 'changeDetail'
                        }
                    })
                },
                null,
                this.handleClose
                )
            })
            // } else {
            //     return false
            // }
            // })

        },

        //取消
        handleClose () {
            this.$router.replace('/PccSetList')
        },
    },
    watch: {
        //冲红单
        'formData.redStatus' () {
            if (this.formData.redStatus == '3') {
                this.redBillStatusStyle.backgroundColor = '#FF2300'
            } else if (
                this.formData.redStatus == '0' ||
                this.formData.redStatus == '1'
            ) {
                this.redBillStatusStyle.backgroundColor = '#FFA40D'
            } else if (this.formData.redStatus == '2') {
                this.redBillStatusStyle.backgroundColor = 'rgb(153,153,153)'
            }
        },
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}
</style>
